import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../components/Layout.vue'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/',
      component: Layout,
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'dashboard',
          component: () => import('../views/DashboardView.vue'),
          meta: { title: '仪表板' }
        },
        {
          path: 'user-role-permission',
          name: 'user-role-permission',
          component: () => import('../views/UserRolePermissionView.vue'),
          meta: { title: '权限管理中心', permissions: ['user:read', 'role:read', 'permission:read'] }
        },
        {
          path: 'modules',
          name: 'modules',
          component: () => import('../views/ModulesView.vue'),
          meta: { title: '模块管理' }
        },
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('../views/NotFoundView.vue'),
      meta: { title: '页面不存在' }
    }
  ],
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 初始化用户状态
  authStore.initUser()
  
  // 设置页面标题
  if (to.meta?.title) {
    document.title = `${to.meta.title} - Home Cloud`
  }
  
  // 不需要登录的页面
  const publicPages = ['/login']
  const authRequired = !publicPages.includes(to.path)
  
  if (authRequired && !authStore.isAuthenticated) {
    // 需要登录但未登录，重定向到登录页
    next('/login')
    return
  }
  
  if (to.path === '/login' && authStore.isAuthenticated) {
    // 已登录用户访问登录页，重定向到仪表板
    next('/dashboard')
    return
  }
  
  // 检查页面权限（仅对需要权限的页面进行检查）
  if (to.meta?.permissions && !['/dashboard', '/profile', '/modules', '/components'].includes(to.path)) {
    const requiredPermissions = to.meta.permissions as string[]
    
    // 等待权限加载完成
    if (authStore.userPermissions.length === 0 && authStore.isAuthenticated) {
      await authStore.loadUserPermissions()
    }
    
    // 检查权限
    if (!authStore.hasAnyPermission(requiredPermissions)) {
      // 没有权限，重定向到仪表板或404页面
      next('/dashboard')
      return
    }
  }
  
  next()
})

export default router
